<!-- C:\Users\王硕\Desktop\毕设\housing-rental-system-frontend\新建文件夹\vue-demo\src\views\UserInfo.vue -->
<template>
  <div class="page-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <span>正在加载个人信息...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-alert type="error" :title="error.message" show-icon />
      <el-button type="primary" @click="retry">重新加载</el-button>
    </div>

    <!-- 正常显示 -->
    <div v-else class="userinfo-container">
      <h2 class="title">个人信息</h2>

      <!-- 基础信息卡片 -->
      <el-card class="info-card">
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/avatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :headers="uploadHeaders"
          >
            <el-avatar
              :size="120"
              :src="userStore.userInfo.avatar"
              class="user-avatar"
            />
            <div class="upload-mask">
              <el-icon :size="24"><Upload /></el-icon>
              <span>更换头像</span>
            </div>
          </el-upload>
          <div class="basic-info">
            <h3>{{ userInfo.nickname }}</h3>
            <p class="account">账号：{{ userInfo.account }}</p>
            <el-button type="primary" @click="showEditDialog" class="edit-btn">
              修改信息
            </el-button>
          </div>
        </div>

        <!-- 详细信息列表 -->
        <el-descriptions :column="1" border>
          <el-descriptions-item label="真实姓名">{{
            userInfo.name || "未设置"
          }}</el-descriptions-item>
          <!-- 手机号显示 -->
          <el-descriptions-item label="手机号">
            {{ formattedPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="电子邮箱">{{
            userInfo.email
          }}</el-descriptions-item>
          <!-- 身份证号显示 -->
          <el-descriptions-item label="身份证号">
            {{ formattedIDCard }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">{{
            genderText
          }}</el-descriptions-item>
          <el-descriptions-item label="职业">{{
            userInfo.job
          }}</el-descriptions-item>
          <el-descriptions-item label="兴趣爱好">{{
            userInfo.hobby
          }}</el-descriptions-item>
          <el-descriptions-item label="个人简介">
            <div class="description-text">{{ userInfo.description }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
  </div>
  <el-dialog
    v-model="editVisible"
    title="修改个人信息"
    width="40%"
    @closed="resetForm"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      label-width="100px"
      :rules="editRules"
    >
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="editForm.nickname" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>

      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>

      <el-form-item label="职业" prop="job">
        <el-input v-model="editForm.job" />
      </el-form-item>

      <el-form-item label="兴趣爱好" prop="hobby">
        <el-input v-model="editForm.hobby" />
      </el-form-item>

      <el-form-item label="个人简介" prop="description">
        <el-input v-model="editForm.description" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="editVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit" :loading="submitting">
        确认修改
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import { useUserStore } from "@/stores/user";
import { formatPhone, formatIdCard } from "@/utils/filters";
import { ElMessage } from "element-plus";
import api from "@/api";
import { Loading, Upload } from "@element-plus/icons-vue";

const userStore = useUserStore();
const loading = ref(false);
const error = ref(null);

// 性别转换
const genderText = computed(() => {
  switch (userStore.userInfo.sex) {
    case 1:
      return "男";
    case 2:
      return "女";
    default:
      return "未知";
  }
});
const formattedIDCard = computed(() => formatIdCard(userStore.userInfo.idCard));

// 组件中
const formattedPhone = computed(() => formatPhone(userStore.userInfo.phone));

const userInfo = computed(() => ({
  ...userStore.userInfo,
  phone: formatPhone(userStore.userInfo.phone),
  idCard: formatIdCard(userStore.userInfo.idCard),
}));

// 上传相关逻辑
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem("token")}`,
}));
const beforeAvatarUpload = (file) => {
  const isValidType = ["image/jpeg", "image/png", "image/webp"].includes(
    file.type
  );
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error("仅支持 JPG/PNG/WEBP 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};
// 上传成功处理
const handleAvatarSuccess = async (response) => {
  console.log("上传成功", response);
  if (response.code === 200) {
    // 更新store中的用户信息
    userStore.setUserInfo({
      ...userStore.userInfo,
      avatar: response.data.avatar,
    });
    ElMessage.success("头像更新成功!");
    window.location.reload();
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};

onMounted(async () => {
  await loadUserInfo();
});

const loadUserInfo = async () => {
  try {
    loading.value = true;
    error.value = null;
    await userStore.fetchUserInfo();
  } catch (err) {
    error.value = err;
  } finally {
    loading.value = false;
  }
};

const retry = () => {
  loadUserInfo();
};

// 新增响应式数据
const editVisible = ref(false);
const submitting = ref(false);
const editFormRef = ref(null);
const editForm = reactive({
  nickname: "",
  phone: "",
  email: "",
  job: "",
  hobby: "",
  description: "",
});

// 验证规则
const editRules = {
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在2到20个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
};

// 显示对话框
const showEditDialog = () => {
  editVisible.value = true;
  Object.assign(editForm, userStore.userInfo);
};

// 提交修改
// 修改submitEdit方法
const submitEdit = async () => {
  try {
    const payload = {
      ...editForm,
      account: userStore.userInfo.account,
      idcard: userStore.userInfo.idcard, // 字段名对齐
    };

    const response = await api.user.updateUserInfo(payload);

    if (response?.code == 200) {
      userStore.setUserInfo(response.data);
      ElMessage.success("修改成功");
      editVisible.value = false;
      window.location.reload();
    } else {
      ElMessage.error(response?.message || "修改失败");
    }
  } catch (error) {
    if (error.response?.status == 401) {
      ElMessage.error("登录已过期，请重新登录");
      router.push("/login");
    } else {
      ElMessage.error(error.message || "网络异常");
    }
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  editFormRef.value?.resetFields();
};
</script>

<style scoped>
.page-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.loading-container {
  text-align: center;
  padding: 50px;
  .el-icon {
    font-size: 40px;
    margin-bottom: 20px;
    animation: rotating 2s linear infinite;
  }
}

.error-container {
  text-align: center;
  padding: 30px;
  .el-alert {
    margin-bottom: 20px;
  }
}

.userinfo-container {
  .title {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
  }
  .info-card {
    padding: 20px;
  }
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

/* 头像上传组件样式 */
.avatar-uploader {
  position: relative;
  margin-right: 30px;
  cursor: pointer;

  &:hover .upload-mask {
    opacity: 1;
  }

  .user-avatar {
    border: 2px solid var(--el-color-primary);
    transition: all 0.3s;
  }

  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;

    .el-icon {
      margin-bottom: 8px;
    }

    span {
      font-size: 12px;
    }
  }
}

.basic-info {
  h3 {
    margin: 0 0 10px;
    font-size: 24px;
  }
  .account {
    color: #666;
    font-size: 14px;
  }
}

.edit-btn {
  margin-top: 10px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  .el-dialog__header {
    background: #f5f7fa;
    border-radius: 8px 8px 0 0;
    margin: 0;
  }
  .el-form-item__label {
    font-weight: 500;
  }
}
</style>
